# Create your views here.
import string
from django.shortcuts       import render_to_response
from django.http            import HttpResponseRedirect
from django.contrib         import auth
from django                 import db
from django.core.mail       import send_mail, EmailMessage

from djangobb.utils         import common_funcs 
from djangobb.users.models  import UserProfile
from django.db              import transaction
import userforms             

def login(request):
    nextPage = common_funcs.get_next_page(request)
    if request.user.is_authenticated():
        return HttpResponseRedirect(nextPage)

    remoteIp = request.META['REMOTE_ADDR']
    forums  = common_funcs.get_forums()
    uname   = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'forums': forums, 'uname': uname,\
                'title': 'Log me in'}
 
    if request.method == 'POST':
        loginForm = userforms.LoginForm(remoteIp, request.POST)
        htmldict['form'] = loginForm
        if not loginForm.is_valid():
            return render_to_response('login.html', htmldict)

        cleanData = loginForm.clean()
        uname = cleanData['uname']
        passwd = cleanData['passwd']
        user = auth.authenticate(username=uname, password=passwd)
        if user is not None:
            if user.is_active:
                auth.login(request, user)
                return HttpResponseRedirect(nextPage)
            else:
                signupForm = userforms.SignupForm(remoteIp)
                htmldict['form'] = signupForm
                htmldict['msg']  = 'Your account has been disabled. You need to sign up again.'
                return render_to_response('register.html', htmldict)
        else:
            htmldict['msg'] = 'Incorrect username/password'
            return render_to_response('login.html', htmldict)
    else:
        loginForm = userforms.LoginForm(remoteIp)
        htmldict['form'] = loginForm
    return render_to_response('login.html', htmldict)

def logout(request):
    nextPage = common_funcs.get_next_page(request)
    auth.logout(request)
    return HttpResponseRedirect(nextPage)

@transaction.commit_on_success
def signup(request):
    nextPage = common_funcs.get_next_page(request)

    remoteIp = request.META['REMOTE_ADDR']
    forums  = common_funcs.get_forums()
    uname   = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'forums': forums, 'uname': uname,\
                'title': 'Create a new account'}

    if request.method == 'POST':
        signupForm = userforms.SignupForm(remoteIp, request.POST)
        htmldict['form'] = signupForm
        if not signupForm.is_valid():
            return render_to_response('register.html', htmldict)

        cleanData = signupForm.clean()
        uname     = cleanData['uname']
        passwd    = cleanData['passwd']
        rptpasswd = cleanData['rptpasswd']
        email     = cleanData['email']
        city      = cleanData['city']
        country   = cleanData['country']
        zip       = cleanData['zip']
 
        if passwd != rptpasswd:
            htmldict['msg'] = 'Passwords did not match. Try again.'
            return render_to_response('register.html', htmldict)

        try:
            user = auth.models.User.objects.create_user(uname, email, password = passwd)
        except db.IntegrityError:
            transaction.rollback()

            htmldict['msg'] = 'Username "%s" has already been taken. Try a  different one.' % uname
            return render_to_response('register.html', htmldict)
            
        try:
            userProfile = UserProfile(user = user, city = city, country = country, zip = zip) 
            userProfile.save()
        except:
            htmldict['msg'] = 'Unknown error: Could not create the user.'
            return render_to_response('register.html', htmldict)
       
        htmldict['msg'] = 'Successfully Created the User'
        return render_to_response('msg.html', htmldict)
    else:
        signupForm = userforms.SignupForm(remoteIp)
        htmldict['form'] = signupForm
        return render_to_response('register.html', htmldict) 

def viewprofile(request):
    nextPage = common_funcs.get_next_page(request)
    forums   = common_funcs.get_forums()
    uname    = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'goback': nextPage, 'forums': forums,\
                'uname': uname, 'title': 'My profile'}

    if request.user.is_authenticated():
        try:
            userProfile = request.user.get_profile()
        except:
            return render_to_response('profile.html', htmldict)

        if userProfile:
            htmldict['userprofile'] = userProfile
            return render_to_response('profile.html', htmldict)
        else:
            htmldict['msg']    = 'Could not find the user profile.'
            return render_to_response('msg.html', htmldict)
    else:
        htmldict['msg']    = 'Anonymous users do not have profile.'
        return render_to_response('msg.html', htmldict)

def chprofile(request):
    nextPage = common_funcs.get_next_page(request)
    forums   = common_funcs.get_forums()
    uname    = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'goback': nextPage, 'forums': forums,\
                'uname': uname, 'title': 'Change your profile'}
 
    # change profile only for valid users
    if request.user.is_authenticated():
        remoteIp = request.META['REMOTE_ADDR']
        # get users profile
        try:           
            userProfile = request.user.get_profile()
        except:
            userProfile = None

        if request.method == 'POST':
            chprofileForm = userforms.ChprofileForm(remoteIp, request.POST)
            htmldict['form'] = chprofileForm
            if not chprofileForm.is_valid():
                return render_to_response('chprofile.html', htmldict)

            cleanData =  chprofileForm.clean()
            city    = cleanData['city']
            country = cleanData['country']
            zip     = cleanData['zip']


            if userProfile:
                userProfile.city    = city
                userProfile.country = country
                userProfile.zip     = zip
            else:  
                userProfile = UserProfile(user=request.user, city= city, \
                              country=country, zip=zip)
 
            # now save the profile
            try:
                userProfile.save()   
            except:
                htmldict['msg'] = 'Could not change the profile. Try again.'
                return render_to_response('chprofile.html', htmldict)

            # successfully changed the profile
            htmldict['msg'] = 'Successfully changed the profile'
            return render_to_response('msg.html', htmldict)
        else:
            if userProfile == None: 
                chprofileForm = userforms.ChprofileForm(remoteIp)
            else:
                userInfo = {'city': userProfile.city, 'country': \
                            userProfile.country, 'zip': userProfile.zip}
                chprofileForm = userforms.ChprofileForm(remoteIp, userInfo)
            htmldict['form'] = chprofileForm
            return render_to_response('chprofile.html', htmldict)
    else:
        htmldict['msg'] = 'You need to login before you change your profile.'
        return render_to_response('msg.html', htmldict)

def passwdrst(request):
    nextPage = common_funcs.get_next_page(request)
    forums   = common_funcs.get_forums()
    uname    = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'goback': nextPage, 'forums': forums,\
                'uname': uname, 'title': 'Reset my password'}
 
    if request.user.is_authenticated():
        htmldict['msg'] = '''You are already logged in. You can instead 
                             change your password'''
        return render_to_response('msg.html', htmldict)
    else:
        # display the passwd reset form
        remoteIp = request.META['REMOTE_ADDR']
        if request.method != 'POST':
            passwdResetForm = userforms.PasswdResetForm(remoteIp)
            htmldict['form'] = passwdResetForm
        else:
            passwdResetForm = userforms.PasswdResetForm(remoteIp, request.POST)
            htmldict['form'] = passwdResetForm

            if not passwdResetForm.is_valid():
                return render_to_response('passwd_reset.html', htmldict)

            cleanData = passwdResetForm.clean()
            uname     = cleanData['uname']
            city      = cleanData['city']
            country   = cleanData['country']
            zip       = cleanData['zip']
            try:
                user      = auth.models.User.objects.get(username__exact=uname)
                try:
                    userProfile = user.get_profile()
                except:
                    htmldict['msg'] = 'The password for this user cannot be reset.'
                    return render_to_response('msg.html', htmldict)
               
                if userProfile.city == city and userProfile.country == country and userProfile.zip == zip:
                    # reset the password
                    new_pass = auth.models.User.objects.make_random_password()
                    user.set_password(new_pass)
                    user.save()
                    mailsubject = 'Password reset on indiankanoon.com'
                    mailcontent = '''For user %s, password has been 
                                  successfully reset to %s  on indiankanoon.com
                                  ''' % (user.username, new_pass)

                    send_mail(mailsubject, mailcontent, \
                              'admin@indiankanoon.com', [user.email])
                    htmldict['msg'] = '''Password resetted and the new password
                                         has been sent to your email address.'''
                    return render_to_response('msg.html', htmldict)
                else:
                    htmldict['msg'] = 'The values are incorrect. Try again.' 
                    return render_to_response('passwd_reset.html', htmldict)
            except:
                htmldict['msg'] = 'No user with name %s exists.' % uname
                return render_to_response('passwd_reset.html', htmldict)

        return render_to_response('passwd_reset.html', htmldict)

def chpasswd(request):
    remoteIp = request.META['REMOTE_ADDR']
    nextPage = common_funcs.get_next_page(request)
    forums   = common_funcs.get_forums()
    uname    = common_funcs.get_uname(request)
    htmldict = {'nextpage': nextPage, 'goback': nextPage, 'forums': forums,\
                'uname': uname, 'title': 'Change my password'}

    if not request.user.is_authenticated():
        htmldict['msg'] = 'You cannot change password of anonymous user'
        return render_to_response('msg.html', htmldict)

    # password change
    if request.method == 'POST':
            chpasswdForm = userforms.ChpasswdForm(remoteIp, request.POST)
            htmldict['form'] = chpasswdForm
            if not chpasswdForm.is_valid():
                return render_to_response('passwd_change.html', htmldict)

            cleanData =  chpasswdForm.clean()
            oldpasswd = cleanData['oldpasswd']
            newpasswd = cleanData['newpasswd']
            rptpasswd = cleanData['rptpasswd']
            # check if passwd is correct and newpasswd = rptpasswd
            if request.user.check_password(oldpasswd):
                if newpasswd == rptpasswd:   
                     try: 
                         request.user.set_password(newpasswd)
                         request.user.save()
                     except:
                         htmldict['msg']='Could not change password. Try again.'
                         return render_to_response('passwd_change.html', htmldict)
                     # Succcess
                     htmldict['msg'] = 'Successfully changed the password.'
                     return render_to_response('msg.html', htmldict)
                else:
                    htmldict['msg'] = 'New passwords dont match.'
                    return render_to_response('passwd_change.html', htmldict)
            else:
                htmldict['msg'] =  'Current password is wrong.'
                return render_to_response('passwd_change.html', htmldict)
    else:
        chpasswdForm = userforms.ChpasswdForm(remoteIp)
        htmldict['form'] = chpasswdForm
    return render_to_response('passwd_change.html', htmldict)
